<template>
  <div class="layout">
    <van-nav-bar title="购物车" left-text="返回" right-text="清空" @click-right="onClickRight" left-arrow
      @click-left="onClickLeft" fixed />

    <div class="content">
      <van-swipe-cell v-for="cart in cartList">
        <van-checkbox :key="cart.cartid" v-model="readonly(cart).flag" @click="onToggleItem(cart.cartid, !cart.flag)" />
        <van-card :price="cart.originprice * cart.discount / 10" currency="¥" :title="cart.proname" :thumb="cart.img1">

          <template #footer>
            <van-stepper :default-value="cart.num" theme="round" button-size="22" disable-input
              @change="(newNum) => onNumChange(cart.cartid, newNum)" />
          </template>
        </van-card>

        <template #right>
          <van-button @click="carOut(cart.cartid)" square text="删除" type="danger" style="height:100%"
            class="delete-button" />
        </template>

      </van-swipe-cell>

    </div>
    <div class="footer">
      <van-submit-bar :price="totalMoney * 100" button-text="提交订单" @submit="onSubmit">
        <van-checkbox v-model="isAll">全选</van-checkbox>
        <template #tip>
          使用微信支付立减 5 元
        </template>
      </van-submit-bar>
    </div>
  </div>
</template>
<script setup lang="ts">
import { readonly, computed } from 'vue'
import { storeToRefs } from 'pinia'
// import { debounce } from 'lodash'
// 使用 vueuse 的 useDebounceFn 函数替代 lodash 的 debounce
import { useDebounceFn } from '@vueuse/core'


import { useCartStore } from '../store/cart'
import { CarOut, OutOver } from '../api/car'
import router from '@/router'
import { locStub } from '@vue/compiler-core'
const cartStore = useCartStore()
const onClickLeft = () => history.back();
const { cartList, totalMoney, isAllSelected, } = storeToRefs(cartStore)

const userid: any = localStorage.getItem('id')

// 全选
const isAll = computed({
  get() {
    return isAllSelected.value
  },
  set(val) {
    // if (val) {
    //   // 全选
    //   cartStore.toggleAll(true)
    // } else {
    //   // 全不选
    //   cartStore.toggleAll(false)
    // }
    cartStore.toggleAll(val)
  }
})



// 请求购物车数据
cartStore.fetchCartList()

const onSubmit = () => {
  console.log('提交订单')
  router.push({ name: 'confirmorder' })
}

// const onNumChange = (cartid: string, num: number) => {
//   cartStore.updateCartNum(cartid, num)
// }

// 修改数量
// 使用 debounce 防抖
const onNumChange = useDebounceFn(
  (cartid: string, num: number) => {
    cartStore.updateCartNum(cartid, num)
  },
  500
)

const onToggleItem = (cartid: string, flag: boolean) => {
  cartStore.toggleCartItem(cartid, flag)
}

// 删除单个
const carOut = async (cartid: string) => {
  console.log(cartid)
  await cartStore.OutCar( cartid )
  cartStore.fetchCartList()
}




// 删除全部
const onClickRight = () => {
  OutOver(userid).then(result => {
    console.log(result)
    cartStore.fetchCartList()
  });

}
</script>

<style>
.content {
  margin-top: 50px;
  margin-bottom: 100px;
}
</style>